package org.openapi.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.openapi.common.ApiResult;
import org.openapi.domain.ApiExchange;
import org.openapi.parser.DataParser;
import org.openapi.service.IDbService;
import org.openapi.service.IOpenExchangeService;
import org.openapi.utils.JsUtil;
import org.openapi.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class OpenExchangeServiceImpl implements IOpenExchangeService {
    @Autowired
    private IDbService dbService;
    /**
     * 读接口
     * @param exchange 接口对象
     * @param dataStr 表单
     * @return
     */
    @Override
    public ApiResult doRead(ApiExchange exchange, String dataStr){
        String sql = exchange.getRead();
        if(JsUtil.isFun(sql)){
            sql = JsUtil.eval(exchange.getRead(), dataStr);
        }
        List<Map<String,Object>> list = dbService.query(sql);
        return ApiResult.success(JsUtil.exec(exchange.getWrite(), list));
    }

    /**
     * 写接口
     * @param exchange 接口对象
     * @param dataStr 表单
     * @return
     */
    @Override
    @Transactional
    public ApiResult doWrite(ApiExchange exchange, String dataStr){
        if(!JsUtil.isFun(exchange.getRead())){
            return ApiResult.error("接口有误");
        }

        int rows = 0;
        String retStr = JsUtil.eval(exchange.getRead(), dataStr);
        RelData data = DataParser.parseData(retStr);
        Map<String, Map> retMap = new HashMap<>();
        for(TableData table: data.getTables()){
            table.setIgnore(false);
            Map<String, Object> dataMap = table.getData();
            dbService.relData(retMap, dataMap);
            rows += dbService.insertData(table, true);
            retMap.put(table.getTable(), dataMap);
        }
        return ApiResult.success(JsUtil.exec(exchange.getWrite(), retMap));
    }

}
